import React, { useState, useEffect, useReducer } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addToTen, fetchCityList } from './store/modules/cityStore';
// import axios from 'axios';
export default function App() {
  const [count, setCount] = useState(0);

  // const handleClick = () => {
  //   setCount(count + 1);
  // };
  return (
    <div>
      <h1>Click count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increase</button>
      <Welcome name="react" />
      <Timer />
      <Counter />
      {/* <GetData /> */}
      <GetCity />
    </div>
  )
}

function UserProfile() {
  const user = {
    name: '申伟',
    age: 25,
    location: '中国',
  };
  const { name, age, location } = user
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>Location: {location}</p>
    </div>
  );
}
function Welcome({ name }) {

  return <h1>Hello, {name}!</h1>;
}
function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []); // 空数组作为第二个参数表示仅在组件挂载和卸载时执行

  return <p>Timer: {seconds} seconds</p>;
}
// function GetData() {
//   const [state, setState] = useState([])
//   useEffect(() => {
//     axios.get('http://localhost:5000').then(res => {
//       setState(res.data)
//     })
//   }, [])
//   return (
//     <ul>
//       {state.map(item => {
//         return <li key={item.id}>{item.cname}</li>
//       })}
//     </ul>
//   )
// }
function counterReducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 }
    case 'decrement':
      return { count: state.count - 1 }
    default:
      throw new Error()
  }
}
function Counter() {
  const [state, dispatch] = useReducer(counterReducer, { count: 0 })
  return (
    <div>
      <p>计数:{state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  )
}
function GetCity() {
  const { cityList, count } = useSelector(state => state.cityReducer)
  const dispatch = useDispatch()
  return (
    <div>
      <div>{count}</div>
      <button onClick={() => dispatch(addToTen(20))}>+20</button>
      <ul>
        {cityList.map(item => <li key={item.id}>{item.cname}</li>)}
      </ul>
      <button onClick={() => dispatch(fetchCityList())}>添加信息</button>
    </div>
  )
}